# -*- coding: utf-8 -*-

import glob
import os
import openpyxl
from common.utils.common_functions import exit_program


class ExcelRead:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            # 创建新的实例
            instance = super().__new__(cls)
            cls._instance = instance
        return cls._instance

    def __init__(self):
        # 判断实例是否已经初始化
        if not hasattr(self, 'authorization_time'):
            # sheet_1
            self.device_identifier = None
            self.row_device_identifier_pos = -1
            self.row_device_identifier_title = "设备标识"
            self.app_package_name = None
            self.row_app_package_name_pos = -1
            self.row_app_package_name_title = "app包名"
            self.app_startup_activity = None
            self.row_app_startup_activity_pos = -1
            self.row_app_startup_activity_title = "app活动名"
            self.script = None
            self.row_script_pos = -1
            self.row_script_title = "测试脚本名称"
            self.crash_number = None
            self.row_crash_number_pos = -1
            self.row_crash_number_title = "测试崩溃次数限制"
            self.crash_logs_number = None
            self.row_crash_logs_number_pos = -1
            self.row_crash_logs_number_title = "app崩溃日志数量"
            self.monitor_crash_interval = None
            self.row_monitor_crash_interval_pos = -1
            self.row_monitor_crash_interval_title = "app监听时间间隔ms"
            self.click_interval = None
            self.row_click_interval_pos = -1
            self.row_click_interval_title = "点击间隔ms"

            self.test_case_path = "testdata/data_files"
            self.test_case_file_path = None
            self.get_test_case_file_path()
            if not self.can_save_excel():
                exit_program("请关闭该文件后重试。")
            try:
                self.workbook = openpyxl.load_workbook(self.test_case_file_path, read_only=False)  # 明确设置为非只读模式
                self.sheet2 = self.workbook.worksheets[1]
                self.row_titles = [self.sheet2.cell(row=i, column=1).value for i in range(1, self.sheet2.max_row)]
            except Exception as e:
                exit_program(f"Error opening file: {e}")

    # 获取测试数据文件路径
    def get_test_case_file_path(self):
        # 使用 glob 模块查找匹配 app_test*.xlsx 的文件
        all_app_test_files = glob.glob(os.path.join(self.test_case_path, "app_test*.xlsx"))
        print("获取testdata/data_files目录下唯一一个以app_test*.xlsx格式命名的测试文件路径")
        for app_test_file in all_app_test_files:
            print(app_test_file)
        if len(all_app_test_files) == 1:
            self.test_case_file_path = all_app_test_files[0]
            print(f"{self.test_case_file_path}存放数据类型都为文本")
        else:
            exit_program(f"请确保{self.test_case_path}目录下只有一个测试用例文件，文件命名格式：app_test*.xlsx")

    # 判断excel是否能保存数据
    def can_save_excel(self):
        try:
            workbook = openpyxl.load_workbook(self.test_case_file_path)
            sheet = workbook.active
            temp_value = sheet['A1'].value  # 保存原数据
            sheet['A1'] = "Temp Save Test"  # 尝试修改 A1 单元格的值
            workbook.save(self.test_case_file_path)
            # 恢复原数据
            sheet['A1'] = temp_value
            workbook.save(self.test_case_file_path)
            workbook.close()
            return True
        except PermissionError:
            print(f"文件 {self.test_case_file_path} 无法保存，可能已被其他程序锁定。")
            return False
        except Exception as e:
            print(f"保存文件时出现其他错误: {e}")
            return False

    def test_parameter_pos(self):
        all_parameters_available = True
        if self.row_script_title in self.row_titles:
            self.row_script_pos = self.row_titles.index(self.row_script_title)
        else:
            print(f"缺少测试参数: {self.row_script_title}")
            all_parameters_available = False
        if self.row_crash_number_title in self.row_titles:
            self.row_crash_number_pos = self.row_titles.index(self.row_crash_number_title)
        else:
            print(f"缺少测试参数: {self.row_crash_number_title}")
            all_parameters_available = False
        if self.row_device_identifier_title in self.row_titles:
            self.row_device_identifier_pos = self.row_titles.index(self.row_device_identifier_title)
        else:
            print(f"缺少测试参数: {self.row_device_identifier_title}")
            all_parameters_available = False
        if self.row_app_package_name_title in self.row_titles:
            self.row_app_package_name_pos = self.row_titles.index(self.row_app_package_name_title)
        else:
            print(f"缺少测试参数: {self.row_app_package_name_title}")
            all_parameters_available = False
        if self.row_app_startup_activity_title in self.row_titles:
            self.row_app_startup_activity_pos = self.row_titles.index(self.row_app_startup_activity_title)
        else:
            print(f"缺少测试参数: {self.row_app_startup_activity_title}")
            all_parameters_available = False
        if self.row_crash_logs_number_title in self.row_titles:
            self.row_crash_logs_number_pos = self.row_titles.index(self.row_crash_logs_number_title)
        else:
            print(f"缺少测试参数: {self.row_crash_logs_number_title}")
            all_parameters_available = False
        if self.row_monitor_crash_interval_title in self.row_titles:
            self.row_monitor_crash_interval_pos = self.row_titles.index(self.row_monitor_crash_interval_title)
        else:
            print(f"缺少测试参数: {self.row_monitor_crash_interval_title}")
            all_parameters_available = False
        if self.row_click_interval_title in self.row_titles:
            self.row_click_interval_pos = self.row_titles.index(self.row_click_interval_title)
        else:
            print(f"缺少测试参数: {self.row_click_interval_title}")
            all_parameters_available = False
        return all_parameters_available

    def update_sheet2_cell_value(self, row_index, column_index, value):
        self.sheet2.cell(row_index, column_index).value = value
        self.workbook.save(self.test_case_file_path)
